package com.appheader.rongmaphone.utils;

import android.content.Context;

import com.appheader.rongmaphone.cache.file.ResourceFileManager;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.zip.ZipInputStream;

/**
 * Created by lpc on 16/8/22.
 * https://github.com/junrar/junrar
 */

public class CompressFile {


    /**
     * 压缩文件
     *
     * @param srcfile
     *            File[] 需要压缩的文件列表
     * @param zipfile
     *            File 压缩后的文件
     */
    public static void ZipFiles(File[] srcfile, File zipfile) {
        byte[] buf = new byte[1024];
        try {
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
                    zipfile));
            for (int i = 0; i < srcfile.length; i++) {
                FileInputStream in = new FileInputStream(srcfile[i]);
                out.putNextEntry(new ZipEntry(srcfile[i].getName()));
                String str = srcfile[i].getName();
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                out.closeEntry();
                in.close();
            }
            out.close();
            System.out.println("压缩完成.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * zip解压缩
     *
     * @param zipfile
     *            File 需要解压缩的文件
     * @param descDir
     *            String 解压后的目标目录
     */
//    public static void unZipFiles(java.io.File zipfile, String descDir) {
//        try {
//            ZipFile zf = new ZipFile(zipfile);
//            for (Enumeration entries = zf.getEntries(); entries
//                    .hasMoreElements();) {
//                ZipEntry entry = ((ZipEntry) entries.nextElement());
//                String zipEntryName = entry.getName();
//                InputStream in = zf.getInputStream(entry);
//                OutputStream out = new FileOutputStream(descDir + zipEntryName);
//                byte[] buf1 = new byte[1024];
//                int len;
//                while ((len = in.read(buf1)) > 0) {
//                    out.write(buf1, 0, len);
//                }
//                in.close();
//                out.close();
//
//
//                //System.out.println("解压缩完成.");
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }


    /**
     * 解压缩功能.
     * 将zipFile文件解压到folderPath目录下.
     * @throws Exception
     *@deprecated has bug ,would generate other file
     */
    public static int upZipFile(File zipFile, String folderPath)throws java.util.zip.ZipException,IOException {
        //public static void upZipFile() throws Exception{
        ZipFile zfile=new ZipFile(zipFile);
        Enumeration zList=zfile.getEntries();
        ZipEntry ze=null;
        byte[] buf=new byte[1024];
        while(zList.hasMoreElements()){
            ze=(ZipEntry)zList.nextElement();
            String zeName = ze.getName();
            if(ze.isDirectory()){

                LogUtil.d("upZipFile", "zeName = "+zeName);

                String dirstr = folderPath + zeName;
                //dirstr.trim();
                dirstr = new String(dirstr.getBytes("8859_1"), "GB2312");
                LogUtil.d("upZipFile", "str = "+dirstr);
                File f=new File(dirstr);
                f.mkdir();
                continue;
            }
            LogUtil.d("upZipFile", "zeName = "+zeName);
            OutputStream os=new BufferedOutputStream(new FileOutputStream(getRealFileName(folderPath, zeName)));
            InputStream is=new BufferedInputStream(zfile.getInputStream(ze));
            int readLen=0;
            while ((readLen=is.read(buf, 0, 1024))!=-1) {
                os.write(buf, 0, readLen);
            }
            is.close();
            os.close();
        }
        zfile.close();
        LogUtil.d("upZipFile", "finishssssssssssssssssssss");
        //删除原zip包
//        File finishUnZipFile = zipFile;
//        if (finishUnZipFile.exists()&&finishUnZipFile.isFile())
//            finishUnZipFile.delete();
        return 0;
    }

    /**
     * 给定根目录，返回一个相对路径所对应的实际文件名.
     * @param baseDir 指定根目录
     * @param absFileName 相对路径名，来自于ZipEntry中的name
     * @return java.io.File 实际的文件
     * @deprecated
     */
    private static File getRealFileName(String baseDir, String absFileName){
        String[] dirs=absFileName.split("/");
        File ret=new File(baseDir);
        String substr = null;
        if(dirs.length>1){
            for (int i = 0; i < dirs.length-1;i++) {
                substr = dirs[i];
                try {
                    //substr.trim();
                    substr = new String(substr.getBytes("8859_1"), "GB2312");

                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                ret=new File(ret, substr);

            }
            LogUtil.d("upZipFile", "1ret = "+ret);
            if(!ret.exists())
                ret.mkdirs();
            substr = dirs[dirs.length-1];
            try {
                //substr.trim();
                substr = new String(substr.getBytes("8859_1"), "GB2312");
                LogUtil.d("upZipFile", "substr = "+substr);
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            ret=new File(ret, substr);
            LogUtil.d("upZipFile", "2ret = "+ret);
            return ret;
        }
        return ret;
    }


    /**
     * 根据原始rar路径，解压到指定文件夹下.
     * @param srcRarPath 原始rar路径
     * @param dstDirectoryPath 解压到的文件夹
     */
//    public static void unRarFile(String srcRarPath, String dstDirectoryPath) {
//        if (!srcRarPath.toLowerCase().endsWith(".rar")) {
//            System.out.println("非rar文件！");
//            return;
//        }
//        File dstDiretory = new File(dstDirectoryPath);
//        if (!dstDiretory.exists()) {// 目标目录不存在时，创建该文件夹
//            dstDiretory.mkdirs();
//        }
//        Archive a = null;
//        try {
//            a = new Archive(new File(srcRarPath));
//            if (a != null) {
//                a.getMainHeader().print(); // 打印文件信息.
//                FileHeader fh = a.nextFileHeader();
//                while (fh != null) {
//                    if (fh.isDirectory()) { // 文件夹
//                        File fol = new File(dstDirectoryPath + File.separator
//                                + fh.getFileNameString());
//                        fol.mkdirs();
//                    } else { // 文件
//                        File out = new File(dstDirectoryPath + File.separator
//                                + fh.getFileNameString().trim());
//                        //System.out.println(out.getAbsolutePath());
//                        try {// 之所以这么写try，是因为万一这里面有了异常，不影响继续解压.
//                            if (!out.exists()) {
//                                if (!out.getParentFile().exists()) {// 相对路径可能多级，可能需要创建父目录.
//                                    out.getParentFile().mkdirs();
//                                }
//                                out.createNewFile();
//                            }
//                            FileOutputStream os = new FileOutputStream(out);
//                            a.extractFile(fh, os);
//                            os.close();
//                        } catch (Exception ex) {
//                            ex.printStackTrace();
//                        }
//                    }
//                    fh = a.nextFileHeader();
//                }
//                a.close();
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    /**
     * 解压Assets中的文件
     * @param context
     * @param assetName
     * @param outputDirectory
     * @throws IOException
     */
    public static void unZipAssetsToSD(Context context, String assetName, String outputDirectory) throws IOException {
        //创建解压目标目录
        File file = new File(outputDirectory);
        //如果目标目录不存在，则创建
        if (!file.exists()) {
            file.mkdirs();
        }
        InputStream inputStream = null;
        //打开压缩文件
        inputStream = context.getAssets().open(assetName);
        ZipInputStream zipInputStream = new ZipInputStream(inputStream);
        //读取一个进入点
        java.util.zip.ZipEntry zipEntry = (java.util.zip.ZipEntry) zipInputStream.getNextEntry();
        //使用1Mbuffer
        byte[] buffer = new byte[1024 * 1024];
        //解压时字节计数
        int count = 0;
        //如果进入点为空说明已经遍历完所有压缩包中文件和目录
        while (zipEntry != null) {
            //如果是一个目录
            if (zipEntry.isDirectory()) {
                //String name = zipEntry.getName();
                //name = name.substring(0, name.length() - 1);
                file = new File(outputDirectory + File.separator + zipEntry.getName());
                file.mkdir();
            } else {
                //如果是文件
                file = new File(outputDirectory + File.separator
                        + zipEntry.getName());
                //创建该文件
                file.createNewFile();
                FileOutputStream fileOutputStream = new FileOutputStream(file);
                while ((count = zipInputStream.read(buffer)) > 0) {
                    fileOutputStream.write(buffer, 0, count);
                }
                fileOutputStream.close();
            }
            //定位到下一个文件入口
            zipEntry = (java.util.zip.ZipEntry) zipInputStream.getNextEntry();
        }
        zipInputStream.close();
    }

    /**
     * 压缩zip文件
     *
     * @param uid
     */
    public static void unZipFileAndOpenNewPage(String uid) {
        try {
            CompressFile.upZipFile(new File(ResourceFileManager.getStaticWebFileDir(uid) + "/" + "previewZip.zip"),
                    ResourceFileManager.getExamDir(uid));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}